﻿using EasyNetQ;
using EasyNetQ.AutoSubscribe;
using System.Threading.Tasks;
using System;
using VOL.Core.Extensions;
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
//using Confluent.Kafka;
using Common;
using Microsoft.AspNetCore.SignalR;

namespace VOL.WebApi.Controllers.Hubs
{
        //public class RabbitService
        //{
        //    public IBus Bus { get; private set; }
        //    public RabbitService(string host)
        //    {
        //        Bus = RabbitHutch.CreateBus("host=" + host);
        //    Bus.SendReceive.Receive("cnc_1_position", receive =>
        //    {
        //        if (receive!=null)
        //        {
        //            string json= receive.ToString();
        //        }
        //    });


        //    }
        //}

    public class MessageDispatcher : IAutoSubscriberMessageDispatcher
    {
        private readonly IServiceProvider provider;

        public MessageDispatcher(IServiceProvider provider)
        {
            this.provider = provider;
        }

        void IAutoSubscriberMessageDispatcher.Dispatch<TMessage, TConsumer>(TMessage message, CancellationToken cancellationToken)
        {
            using (var scope = provider.CreateScope())
            {
                var consumer = scope.ServiceProvider.GetRequiredService<TConsumer>();
                consumer.Consume(message);
            }
        }

        async Task IAutoSubscriberMessageDispatcher.DispatchAsync<TMessage, TConsumer>(TMessage message, CancellationToken cancellationToken)
        {
            using (var scope = provider.CreateScope())
            {
                var consumer = scope.ServiceProvider.GetRequiredService<TConsumer>();
                await consumer.ConsumeAsync(message);
            }
        }
    }

    public class MyConsumer : IConsume<RabbitCNCMessage>,
    IConsume<MessageB>
    {
        private readonly IHubContext<CncStatusHub> _hubContext;
        public MyConsumer(IHubContext<CncStatusHub> hubContext)
        {
            _hubContext= hubContext;
        }
        public void Consume(RabbitCNCMessage message, CancellationToken cancellationToken = default)
        {
            _hubContext.Clients.All.SendAsync("CncMessage", message);
        }

        public void Consume(MessageB message, CancellationToken cancellationToken = default)
        {
            
        }
    }




}
